package com.jpyl.jpMedicalTreatment.view.activity.home;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.example.lordbasewidget.wheelpicker.view.DateTimePicker;
import com.forxindu.kit.box.DateKit;
import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.ViewKit;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.model.AgentMessageModel;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.OutSituationModel;
import com.jpyl.jpMedicalTreatment.model.OutSituationNumModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;
import com.jpyl.jpMedicalTreatment.view.adapter.OutSituationAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 出货情况
 * Created by 15697 on 2019/3/8.
 */

public class OutSituationActivity extends BaseActivity {
    OutSituationAdapter adapter;
    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;
    @BindView(R.id.right_button)
    TextView right_button;

    @BindView(R.id.time_layout)
    RelativeLayout timeLayout;

    @BindView(R.id.start_time)
    TextView startTimeView;

    @BindView(R.id.end_time)
    TextView endTimeView;


    final RequestApi publicApi = Network.getRequestApi();
    RxSpf_UserModel spfUserModel;
    AgentMessageModel bean;
    List<OutSituationNumModel> list = new ArrayList<>();
    boolean isDoctor;
    String flag = "";
    private long dateFrom = 0;
    private long dateTo = 0;
    private DateTimePicker startTimePicker;
    private DateTimePicker endTimePicker;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_out_situation_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        spfUserModel = RxSpf_UserModel.create(this);
        bean = (AgentMessageModel) getIntent().getSerializableExtra("list");
        flag = getIntent().getStringExtra("flag");
        isDoctor = getIntent().getBooleanExtra("isDoctor", false);
        mTitleTv.setText(bean.getUsername());
        right_button.setText(getString(R.string.selectTime));
        right_button.setVisibility(View.VISIBLE);
        String timeNow = DateKit.dateConvertStringByPattern(new Date(),DateKit.PATTERN4);
        startTimeView.setText(timeNow);
        endTimeView.setText(timeNow);
        adapter = new OutSituationAdapter(getApplicationContext(), list);
        rvRefreshLayout.setAdapter(adapter);
        rvRefreshLayout.setLayoutManager(new GridLayoutManager(this, 1));
        mrRefreshLayout.setLoadMore(false);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                jpylMyPatientStatistics();
                mrRefreshLayout.finishRefreshing();
                mrRefreshLayout.finishRefresh();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                materialRefreshLayout.finishRefreshLoadMore();
            }
        });
        switch (flag) {
            case "1":
                //医生查患者
                jpylMyPatientStatistics();
                break;
            case "2":
                //代理差医生
                jpylAgentDPStatitics(0, bean.getId());
                break;
            case "3":
                //代理差患者
                jpylAgentDPStatitics(1, "");
                break;
            case "4":
                //总代理差代理
                jpylMyAgentStatiticsForAreaAgent();
                break;
        }
        right_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(timeLayout.getVisibility()==View.GONE){
                    timeLayout.setVisibility(View.VISIBLE);
                    initStartTime();
                    startTimePicker.showPicker(startTimeView);
                }
            }
        });
        startTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initStartTime();
                startTimePicker.showPicker(view);
            }
        });
        endTimeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initEndTime();
                endTimePicker.showPicker(view);
            }
        });
    }

    /**
     * 医生差患者
     */
    private void jpylMyPatientStatistics() {

        publicApi.jpylMyPatientStatistics(spfUserModel.userId().get(), bean.getId(), dateFrom,
                dateTo).map(new Func1<ResponseModel<OutSituationModel>, OutSituationModel>() {
            @Override
            public OutSituationModel call(ResponseModel<OutSituationModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OutSituationModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();

//                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(OutSituationActivity.this,error.getMessageModel().getMsg());
                        }
                    }

                    @Override
                    public void onNext(OutSituationModel model) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        mrRefreshLayout.finishRefreshLoadMore();

                        list.clear();
                        list.add(new OutSituationNumModel("艾尔贝清", model.outNum.艾尔贝清));
                        list.add(new OutSituationNumModel("劲络通", model.outNum.劲络通));
                        list.add(new OutSituationNumModel("ELOCK", model.outNum.ELOCK));
                        list.add(new OutSituationNumModel("愈伤带", model.outNum.愈伤带));
                        list.add(new OutSituationNumModel("珍宫夫", model.outNum.珍宫夫));
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 代理差患者和医生
     * 0医生，1患者
     * targetid 医生id，患者出货不传
     */
    private void jpylAgentDPStatitics(int type, String targetid) {

        publicApi.jpylAgentDPStatitics(spfUserModel.userId().get(), targetid, type, dateFrom,
                dateTo).map(new Func1<ResponseModel<OutSituationModel>, OutSituationModel>() {
            @Override
            public OutSituationModel call(ResponseModel<OutSituationModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OutSituationModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(OutSituationActivity.this,error.getMessageModel().getMsg());
                        }
                    }

                    @Override
                    public void onNext(OutSituationModel model) {
                        list.clear();
                        list.add(new OutSituationNumModel("艾尔贝清", model.outNum.艾尔贝清));
                        list.add(new OutSituationNumModel("劲络通", model.outNum.劲络通));
                        list.add(new OutSituationNumModel("ELOCK", model.outNum.ELOCK));
                        list.add(new OutSituationNumModel("愈伤带", model.outNum.愈伤带));
                        list.add(new OutSituationNumModel("珍宫夫", model.outNum.珍宫夫));
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void jpylMyAgentStatiticsForAreaAgent() {
        final JsonObject body = new JsonObject();
        body.addProperty("rows", "10");
        body.addProperty("page", "1");

        publicApi.jpylMyAgentStatiticsForAreaAgent(bean.getId(), body.toString(), dateFrom,
                dateTo).map(new Func1<ResponseModel<OutSituationModel>, OutSituationModel>() {
            @Override
            public OutSituationModel call(ResponseModel<OutSituationModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<OutSituationModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(OutSituationActivity.this,error.getMessageModel().getMsg());
                        }
                    }

                    @Override
                    public void onNext(OutSituationModel model) {
                        list.clear();
                        list.add(new OutSituationNumModel("艾尔贝清", model.outNum.艾尔贝清));
                        list.add(new OutSituationNumModel("劲络通", model.outNum.劲络通));
                        list.add(new OutSituationNumModel("ELOCK", model.outNum.ELOCK));
                        list.add(new OutSituationNumModel("愈伤带", model.outNum.愈伤带));
                        list.add(new OutSituationNumModel("珍宫夫", model.outNum.珍宫夫));
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    //开始时间日期波选器
    private void initStartTime() {
        Calendar startCalendar = Calendar.getInstance(Locale.CANADA);
        if(dateTo!=0){
            Date date = new Date(dateTo);
            startCalendar.setTime(date);
        }else{
            startCalendar.setTime(new Date());
        }
        startTimePicker = new DateTimePicker(this, DateTimePicker.DATE_PICKER, true, "请选择开始时间", new Date(), 10, startCalendar.getTime());
        startTimePicker.generatePicker();
        startTimePicker.setOnPositiveButtonClick(new DateTimePicker.OnDateTimePositiveButtonClick() {
            @Override
            public void onReceivedSelectedDate(Calendar selectedDate, String dateText) {
                dateFrom = selectedDate.getTime().getTime();
                String time = DateKit.dateConvertStringByPattern(selectedDate.getTime(),DateKit.PATTERN4);
                startTimeView.setText(time);
            }

            @Override
            public void onReceivedSelectedTime(Calendar selectedTime, String timeText) {
            }

            @Override
            public void onReceivedSelectedDateTime(Calendar selectedDateTime, String dateTimeText) {
            }
        });
    }

    //结束时间日期波选器
    private void initEndTime() {
        Calendar startCalendar = Calendar.getInstance(Locale.CANADA);
        if(dateFrom!=0){
            Date date = new Date(dateFrom);
            startCalendar.setTime(date);
        }else{
            startCalendar.setTime(new Date());
        }
        endTimePicker = new DateTimePicker(this, DateTimePicker.DATE_PICKER, false, "请选择结束时间", startCalendar.getTime(), startCalendar.getTime(),new Date());
        endTimePicker.generatePicker();
        endTimePicker.setOnPositiveButtonClick(new DateTimePicker.OnDateTimePositiveButtonClick() {
            @Override
            public void onReceivedSelectedDate(Calendar selectedDate, String dateText) {
                dateTo = selectedDate.getTime().getTime();
                String time = DateKit.dateConvertStringByPattern(selectedDate.getTime(),DateKit.PATTERN4);
                endTimeView.setText(time);
            }

            @Override
            public void onReceivedSelectedTime(Calendar selectedTime, String timeText) {

            }

            @Override
            public void onReceivedSelectedDateTime(Calendar selectedDateTime, String dateTimeText) {

            }
        });
    }
}
